<?php

$cacheable = 1;
$enable_profiling = 1;
require_once("sys.inc");

$top = "common";
$content = "player";
$side = "player";

$player_id = 0;

if (isset($_GET["id"]) && preg_match("/^\d+$/", $_GET["id"]))
{
	$player_id = $_GET["id"] + 0; 
}

if ($player_id == 0)
	err("Invalid player ID: " . $_GET["id"]);

$show_datesec = time();
$max_datesec = 0;
$date = "";

$q = "SELECT * FROM $table_rating
LEFT JOIN $table_log 
	ON ($table_rating.tournament_id = $table_log.tournament_id 
		AND $table_rating.player_id = $table_log.player_id) 
WHERE $table_rating.player_id=$player_id 
ORDER BY datesec DESC
";

$plog = Array();

$result = mysql_query($q);
while ($row = mysql_fetch_object($result))
{
	array_push($plog, $row);
}

$last_tid = 0;
$trns = Array();

$pid_cond = Array();
$pid_cond["player_id=" . $player_id]++;

$tid_cond = Array();

function rcmp($a, $b)
{
	if ($a->round_key == $b->round_key)
		return 0;
	return $a->round_key < $b->round_key ? -1 : 1;
}

$t5years = $show_datesec-5*31557600;
$t2years = $show_datesec-2*31557600;
$t1years = $show_datesec-1*31557600;

$g1 = 0;
$g2 = 0;
$g5 = 0;

foreach ($plog as $log)
{
	$pid_cond["player_id=" . $log->opponent_id]++;
	$tid_cond["tournament_id=". $log->tournament_id]++;
	if ($log->tournament_id != $last_tid)
	{
		if (isset($curr))
		{
			usort($curr, "rcmp");
			array_push($trns, $curr);
		}
		$curr = Array();
	}
	array_push($curr, $log);
	$last_tid = $log->tournament_id;
}

if (isset($curr))
{
	usort($curr, "rcmp");
	array_push($trns, $curr);
}

$max_rating = 0;

foreach ($trns as $t)
{
    $log = $t[0];
    if ($log->player_end_rating > $max_rating)
    	$max_rating = $log->player_end_rating; 
	if ($log->datesec >= $t1years)
	{
	    $g1 += $log->g;
	    $g2 += $log->g;
	    $g5 += $log->g;
	}
	elseif ($log->datesec >= $t2years)
	{
	    $g2 += $log->g;
	    $g5 += $log->g;
	}
	elseif ($log->datesec >= $t5years)
	{
	    $g5 += $log->g;
	}
}

$pdict = get_pdict(join(" OR ", array_keys($pid_cond)));
$player = $pdict[$player_id];
$player->g1 = $g1;
$player->g2 = $g2;
$player->g5 = $g5;

if (!isset($player))
	err("Player ID=$player_id not found", "Bad news, everyone!");

	
$tdict = Array();
$cond = join(" OR ", array_keys($tid_cond));
if ($cond == "")
	$cond = "0";
	
$q = "SELECT * FROM $table_tournament WHERE $cond";
$result = mysql_query($q);
while ($row = mysql_fetch_object($result))
{
	$tdict[$row->tournament_id] = $row;
}

require 'tpl/index.tpl';

?>